package net.jjjshop.common.util.alimini;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.parser.Feature;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipayEncrypt;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import net.jjjshop.common.entity.third.AliminiAuthUser;
import org.springframework.context.annotation.Configuration;

import java.util.Map;

import static net.jjjshop.common.util.alimini.AliminiConfig.*;

/**
 * 获取支付宝用户基本信息
 */
@Configuration
@Slf4j
public class AlipaySystemOauthTokenUtils {
    /**
     *
     * @param authCode 用授权码来换取授权令牌: authorization_code,用刷新令牌来换取一个新的授权令牌: refresh_token
     * @param grantType  用授权码来换取授权令牌: authorization_code ,用刷新令牌来换取一个新的授权令牌: refresh_token
     * @throws AlipayApiException
     */
    public  AliminiAuthUser getAlipaySystemOauthToken(String authCode,String grantType)  {
        // 初始化SDK
        AlipayClient alipayClient = new DefaultAlipayClient(URL, APPID, RSA_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGNTYPE);

        // 构造请求参数以调用接口
        AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();

        if (grantType.equals("refreshToken")) {
            request.setRefreshToken(authCode);
        }

        if (grantType.equals("authorization_code")) {
            request.setCode(authCode);
        }

        // 设置授权码
//        request.setCode(authCode);
        
        // 设置授权方式
        request.setGrantType(grantType);

        AlipaySystemOauthTokenResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
        System.out.println(response.getBody());

        if (response.isSuccess()) {
            System.out.println("调用成功");
            JSONObject jsonObject = JSONObject.parseObject(response.getBody());
            JSONObject alipaySystemOauthTokenResponse = jsonObject.getJSONObject("alipay_system_oauth_token_response");
           /* alipaySystemOauthTokenResponse.getString("user_id");
            alipaySystemOauthTokenResponse.getString("open_id");
            alipaySystemOauthTokenResponse.getString("access_token");
            alipaySystemOauthTokenResponse.getString("expires_in");
            alipaySystemOauthTokenResponse.getString("refresh_token");
            alipaySystemOauthTokenResponse.getString("re_expires_in");*/
            System.out.println("获取user_id info :"+response.getBody());
            AliminiAuthUser aliminiAuthUser = new AliminiAuthUser().setUserId(alipaySystemOauthTokenResponse.getString("user_id"))
                    .setOpenId(alipaySystemOauthTokenResponse.getString("open_id"))
                    .setAccessToken(alipaySystemOauthTokenResponse.getString("access_token"));

            return aliminiAuthUser;
            /**
             * {
             *     "alipay_system_oauth_token_response": {
             *         "user_id": "2088102150477652",
             *         "open_id": "074a1CcTG1LelxKe4xQC0zgNdId0nxi95b5lsNpazWYoCo5",
             *         "access_token": "20120823ac6ffaa4d2d84e7384bf983531473993",
             *         "expires_in": "3600",
             *         "refresh_token": "20120823ac6ffdsdf2d84e7384bf983531473993",
             *         "re_expires_in": "3600",
             *         "auth_start": "2010-11-11 11:11:11"
             *     },
             *     "sign": "ERITJKEIJKJHKKKKKKKHJEREEEEEEEEEEE"
             * }
             */
        } else {
            System.out.println("调用失败");
            // sdk版本是"4.38.0.ALL"及以上,可以参考下面的示例获取诊断链接
             System.out.println(response.toString());
            return null;
        }
    }

    /**
     * 解密手机号
     * @param response
     * @return
     * @throws Exception
     */
    public  String getPhoneNumber(String sign,String encryptedData) {
        //1. 获取验签和解密所需要的参数
//       Map<String, String> openapiResult = JSON.parseObject(response,new TypeReference<Map<String, String>>() {}, Feature.OrderedField);

        String signType = "RSA2";
        String charset = "UTF-8";
        String encryptType = "AES";
        String content = encryptedData;

        //判断是否为加密内容
        boolean isDataEncrypted = !content.startsWith("{");
        boolean signCheckPass = false;
        //2. 验签
        String signContent = content;
        String signVeriKey = ALIPAY_PUBLIC_KEY;
        String decryptKey = DECRYPT_KEY;//如果是加密的报文则需要在密文的前后添加双引号

        if (isDataEncrypted) {
            signContent = "\"" + signContent + "\"";
        } try {
            signCheckPass = AlipaySignature.rsaCheck(signContent, sign, signVeriKey, charset, signType);
        } catch (AlipayApiException e) {
            // 验签异常, 日志
            log.error(e.getMessage());
        } if (!signCheckPass) {
            //验签不通过（异常或者报文被篡改），终止流程（不需要做解密）
            log.error("验签不通过（异常或者报文被篡改），终止流程（不需要做解密");
           return null;
        }
        //3. 解密
        String plainData = null;
        if (isDataEncrypted) {
            try {
                plainData = AlipayEncrypt.decryptContent(content, encryptType, decryptKey, charset);
                JSONObject phone = JSONObject.parseObject(plainData);
                if (phone.getString("code").equals("10000")) {
                    return phone.getString("mobile");
                }
                return plainData;
            } catch (AlipayApiException e) {
                //解密异常, 记录日志
                log.error( e.getMessage());
            }} else {
            plainData = content;
        }
        return null;
    }

 /*   public static void main(String[] args) {

            String p = "{\n" +
                "    \"errMsg\": \"getPhoneNumber:ok\",\n" +
                "    \"encryptedData\": \"P6zIgtC5X5abxPT2gbjLOdEIT5EpNwTBFq22ih8VbrYHp4kfPSnaAYvvbyGw4pgr9vvVySMVvnIkXsSky3mwCA==\",\n" +
                "    \"sign\": \"YNJRJ3evK18iAwIAcdDcPTWRnF6qqoA4LMPAq190MlBt7ngNZAox7FX7sm9gQ8ywxm4IFlZOtfCG1JZOfPVtICkr46H9HkI+wPcYXOdzlVfpFaWehcdqw6zWKs1CEXf6bNcRgTUGadokzV/CkVMKrEjgsqQ9hQoH3rQoVt2Dojkl2At3lexTXIqvxiAu1VZbmKQgKz5XpNdHSWsFrmIoVzr5bu7y/AySwmA6RVUNDZY4JvOS0zLa93Tqp5kp2C85ZWb/ChMa/xRAfAJ80a/ZqYhHKt7J3xEaq+5lvWDp5zhS8pyice/Hx5QatH5B90Di7lpCG+Y6tlZIeOu7atwx8w==\"\n" +
                "}";

        try {
            System.out.println(getPhoneNumber(p) );
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }*/

}